package service;

import entity.Product;
import utils.DatabaseUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class ProductService {

    // 查询商品
    public Product queryProduct(String region, Long productId) throws Exception {
        Connection conn = DatabaseUtil.getConnection(region);
        String sql = "SELECT * FROM product WHERE id = ?";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setLong(1, productId);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                Product product = new Product();
                product.setId(rs.getLong("id"));
                product.setName(rs.getString("name"));
                product.setTotalStock(rs.getInt("total_stock"));
                product.setAvailableStock(rs.getInt("available_stock"));
                return product;
            }
        }
        return null;
    }

    // 购买商品
    public boolean purchaseProduct(Long productId, int quantity) throws Exception {
        Connection conn = DatabaseUtil.getConnection("master");
        String sql = "UPDATE product SET available_stock = available_stock - ? WHERE id = ? AND available_stock >= ?";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, quantity);
            stmt.setLong(2, productId);
            stmt.setInt(3, quantity);
            return stmt.executeUpdate() > 0;
        }
    }

    // 退货商品
    public boolean returnProduct(Long productId, int quantity) throws Exception {
        Connection conn = DatabaseUtil.getConnection("master");
        String sql = "UPDATE product SET available_stock = available_stock + ? WHERE id = ?";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, quantity);
            stmt.setLong(2, productId);
            return stmt.executeUpdate() > 0;
        }
    }
}